package pers.cj.pdos.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import pers.cj.pdos.controller.base.BaseController;
import pers.cj.pdos.controller.entity.ResponseData;
import pers.cj.pdos.controller.entity.ResponseEntity;
import pers.cj.pdos.controller.entity.ResponseList;
import pers.cj.pdos.entity.*;
import pers.cj.pdos.service.ICheckHouseService;
import pers.cj.pdos.service.IGoodsCostService;
import pers.cj.pdos.utils.DataUtil;
import pers.cj.pdos.utils.PdosUtils;
import pers.cj.pdos.utils.Utils;
import pers.cj.pdos.utils.UuidUtils;
import pers.cj.pdos.vo.*;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chenj
 * @since 2019-11-04
 */
@Controller
@RequestMapping("/house")
public class CheckHouseController extends BaseController {
    @Autowired
    ICheckHouseService checkHouseService;
    @Autowired
    IGoodsCostService goodsCostService;

    @RequiresPermissions("checkHouse:query")
    @RequestMapping("/checkHouse")
    public String checkHouse(){
        return "checkHouse/checkHouse";
    }

    @RequiresPermissions("checkHouse:insert")
    @RequestMapping("/checkHouseNew")
    public String checkHouseNew(){
        return "checkHouse/checkHouseNew";
    }

    @RequiresPermissions("checkHouse:query")
    @RequestMapping("/checkHouseDetail")
    public String checkHouseDetail(Model model, String id){
        model.addAttribute("id",id);
        return "checkHouse/checkHouseDetail";
    }

    @ResponseBody
    @RequiresPermissions("checkHouse:query")
    @RequestMapping("/checkHouse/getList")
    public ResponseList getList(int page,
                                int limit,
                                String close,
                                String search,
                                String no,
                                String goodsName,
                                String remark,
                                String date1,
                                String date2,
                                String storeId,
                                String userId,
                                String makeTime1,
                                String makeTime2,
                                String houseId,
                                String makeUserId){
        Company company = getCompany();
        UserVo userVo = getLoginUserVo();


        List<CheckHouseVo> list = checkHouseService.listVo(company.getId(),
                page,
                limit,
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                storeId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                houseId,
                makeUserId);
        long count = checkHouseService.count(company.getId(),
                Utils.genBoolean(close),
                Utils.genLikeData(search),
                Utils.genLikeData(no),
                Utils.genLikeData(goodsName),
                Utils.genLikeData(remark),
                Utils.genDate(makeTime1),
                Utils.genDate(makeTime2),
                storeId,
                PdosUtils.getViewOrderStoreId(userVo,null),
                PdosUtils.getViewOrderUserId(userVo,userId),
                Utils.genDate(date1),
                Utils.genDate(date2),
                houseId,
                makeUserId);
        return ResponseList.success(count,list);
    }

    @ResponseBody
    @RequiresPermissions("checkHouse:insert")
    @RequestMapping("/checkHouse/add")
    public ResponseEntity add(@RequestBody CheckHouseVo checkHouseVo){

        Company company = getCompany();

        if (Utils.isEmpty(checkHouseVo.getNo())){
            return ResponseEntity.fail("编号不能为空");
        }

        if (Utils.isEmpty(checkHouseVo.getCheckHouseGoodsVoList())){
            return ResponseEntity.fail("请选择盘点商品");
        }

        if (checkHouseVo.getDate() == null){
            return ResponseEntity.fail("业务日期不能为空");
        }

        if (checkHouseService.checkNo(checkHouseVo.getNo(),company.getId())){
            return ResponseEntity.fail("编号已被使用");
        }

        if (!getHouseLocking(checkHouseVo.getHouseId())) {
            return ResponseEntity.fail("盘点仓库未被锁定，请锁定仓库");
        }


        CheckHouse checkHouse = DataUtil.genEntityFromVo(CheckHouse.class,checkHouseVo);
        DataUtil.processEntity(company,checkHouse);
        checkHouse.setClose(false);
        checkHouse.setMakeUserId(getLoginUserId());
        checkHouse.setMakeTime(checkHouse.getTime());


        List<GoodsCost> list = goodsCostService.listByGoodsList(checkHouseVo.getCheckHouseGoodsVoList());
        Map<String,GoodsCost> map = DataUtil.genMap("goodsId", list);

        BigDecimal total_add = new BigDecimal(0);//盘盈总金额
        BigDecimal total_del = new BigDecimal(0);//盘亏总金额

        Integer status = 2;

        List<CheckHouseGoods> checkHouseGoodsList = new ArrayList<>();
        List<CheckHouseGoodsSn> checkHouseGoodsSnList = new ArrayList<>();

        List<GoodsSn> addGoodsSnList = new ArrayList<>();//新增的sn
        List<GoodsSn> delGoodsSnList = new ArrayList<>();//新增的sn
        List<GoodsSnLog> goodsSnLogList = new ArrayList<>();//需要新增的log
        Map<String,Object> snInitMap = new HashMap<>();
        snInitMap.put("inDate", new Date());//设置入库日期
        snInitMap.put("status", 1);//设置状态为未出库
        for (CheckHouseGoodsVo vo:checkHouseVo.getCheckHouseGoodsVoList()) {
            CheckHouseGoods entity = DataUtil.genEntityFromVo(CheckHouseGoods.class, vo);
            DataUtil.processEntity(company,entity);
            entity.setCheckHouseId(checkHouse.getId());
            if (map.containsKey(entity.getGoodsId())) {
                entity.setCost(map.get(entity.getGoodsId()).getCost());
            } else {
                entity.setCost(new BigDecimal(0));
            }


            entity.setAddAmount(new BigDecimal(0));
            entity.setDelAmount(new BigDecimal(0));
            entity.setAddAmount(new BigDecimal(0));
            entity.setDelAmount(new BigDecimal(0));
            if (entity.getNumber().compareTo(entity.getStockNum()) == 1) {
                //盘盈
                entity.setAddNumber(entity.getNumber().subtract(entity.getStockNum()));
                entity.setAddAmount(entity.getAddNumber().multiply(entity.getCost()));
                total_add = total_del.add(entity.getAddAmount());
                status = 1;
            } else if (entity.getNumber().compareTo(entity.getStockNum()) == -1) {
                //盘亏
                entity.setDelNumber(entity.getStockNum().subtract(entity.getNumber()));
                entity.setDelAmount(entity.getDelNumber().multiply(entity.getCost()));
                total_del = total_del.add(entity.getDelAmount());
                status = 1;
            }

            checkHouseGoodsList.add(entity);

            if (!Utils.isEmpty(vo.getAddGoodsSnList())){
                for (GoodsSn goodsSn : vo.getAddGoodsSnList()) {
                    DataUtil.processEntity(company, goodsSn,snInitMap);
                    addGoodsSnList.add(goodsSn);

                    goodsSnLogList.add(genGoodsSnLog(15,goodsSn,entity));
                    checkHouseGoodsSnList.add(genCheckHouseGoodsSn(2, goodsSn,entity));
                }
            }

            if (!Utils.isEmpty(vo.getDelGoodsSnList())){
                for (GoodsSn goodsSn : vo.getDelGoodsSnList()) {
                    delGoodsSnList.add(goodsSn);

                    goodsSnLogList.add(genGoodsSnLog(16,goodsSn,entity));
                    checkHouseGoodsSnList.add(genCheckHouseGoodsSn(3, goodsSn,entity));
                }
            }

            if (!Utils.isEmpty(vo.getFitGoodsSnList())){
                for (GoodsSn goodsSn : vo.getFitGoodsSnList()) {
                    checkHouseGoodsSnList.add(genCheckHouseGoodsSn(1, goodsSn,entity));
                }
            }
        }


        checkHouse.setAddAmount(total_add);
        checkHouse.setDelAmount(total_del);
        checkHouse.setStatus(status);
        checkHouseService.insert(checkHouse,checkHouseGoodsList, checkHouseGoodsSnList, addGoodsSnList, delGoodsSnList,goodsSnLogList);

        return ResponseEntity.success();
    }

    @ResponseBody
    @RequiresPermissions("checkHouse:close")
    @RequestMapping("/checkHouse/close")
    public ResponseEntity close(@RequestBody CheckHouse checkHouse){
        //检查是否已经关闭
        if (checkHouseService.checkClose(checkHouse)){
            return ResponseEntity.fail("该单据已被关闭，不能重复关闭");
        }

        try {
            checkHouseService.close(checkHouse);
            return ResponseEntity.success();
        }catch (Exception e) {
            return ResponseEntity.fail("关闭订单失败");
        }
    }

    @ResponseBody
    @RequestMapping("/checkHouse/getVoById")
    public ResponseData getVoById(String id) {
        return ResponseData.success(checkHouseService.getVoById(id));
    }


    private GoodsSnLog genGoodsSnLog(int type, GoodsSn goodsSn, CheckHouseGoods entity){
        GoodsSnLog log = new GoodsSnLog();
        log.setId(UuidUtils.getUUID());
        log.setTime(new Date());
        log.setCompanyId(entity.getCompanyId());
        log.setGoodsId(goodsSn.getGoodsId());
        log.setSn(goodsSn.getSn());
        log.setType(type);
        log.setCheckHouseGoodsId(entity.getId());
        return log;
    }

    private CheckHouseGoodsSn genCheckHouseGoodsSn(int status,GoodsSn goodsSn, CheckHouseGoods entity){

        CheckHouseGoodsSn checkHouseGoodsSn = new CheckHouseGoodsSn();
        checkHouseGoodsSn.setId(UuidUtils.getUUID());
        checkHouseGoodsSn.setCompanyId(entity.getCompanyId());
        checkHouseGoodsSn.setGoodsId(entity.getGoodsId());
        checkHouseGoodsSn.setSn(goodsSn.getSn());
        checkHouseGoodsSn.setCheckHouseGoodsId(entity.getId());
        checkHouseGoodsSn.setStatus(status);
        return checkHouseGoodsSn;
    }
}
